<template>
  <el-dialog
    v-model="dialogVisible"
    title="曲线分析"
    width="80%"
    :append-to-body="true"
    :destroy-on-close="false"
    :before-close="close"
    @close="close"
    top="20px"
  >
    <el-card class="card-container">
      <el-form :model="searchFrom">
        <el-row :gutter="24">
          <el-col :span="5">
            <el-form-item label="站点名称:" label-width="80px">
              <el-input v-model="searchFrom.name" placeholder="请输入站点名称" />
            </el-form-item>
            <el-form-item label="识别类型:" label-width="80px">
              <el-select v-model="searchFrom.type" placeholder="请选择识别类型" clearable>
                <el-option
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="昆虫:" label-width="80px">
              <el-select v-model="searchFrom.range" placeholder="请选择昆虫" clearable>
                <el-option
                  v-for="item in insectList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="时间:" label-width="80px">
              <el-date-picker
                v-model="searchFrom.time"
                type="datetimerange"
                :shortcuts="shortcuts"
                range-separator="和"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" size="small" icon="search" @click="menuSearch"
              >搜索</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="card-container">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-table
            :data="insectSituationList"
            row-key="id"
            :empty-text="'暂无数据'"
            stripe
            border
            max-height="50vh"
            :show-header="false"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection"></el-table-column>
            <el-table-column label="站点名称" prop="title" align="center" />
          </el-table>
          <pagination
            v-if="totals > 0"
            :total="totals"
            @update:current-page="handleCurrentPageUpdate"
            @update:page-size="handlePageSizeUpdate"
          ></pagination>
        </el-col>
        <el-col :span="18">
          <div ref="tableChart" class="chart-container"></div>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script setup lang="ts">
//系统配置
import { ref, reactive, toRefs, onMounted, onBeforeMount, watchEffect } from 'vue'

import * as echarts from 'echarts'
import { title } from 'process'

//业务模型
const state = reactive({
  searchFrom: {
    type: 1,
    range: 1,
    time: [],
    name: '',
    startTime: '',
    EndTime: '',
    current: 1,
    size: 10
  },
  typeList: [
    { value: 1, label: 'D2识别' },
    { value: 2, label: 'D1识别' },
    { value: 3, label: 'G识别' }
  ],
  insectList: [],
  totals: 0,
  insectSituationList: [
    {
      id: 1,
      title: '站点名称1'
    },
    {
      id: 2,
      title: '站点名称2'
    }
  ],
  multipleSelection: [],
  echartsList: [
    { date: '2025-07-14', name: '二点委夜蛾', count: '42' },
    { date: '2025-07-14', name: '铜绿异丽金龟', count: '84' },
    { date: '2025-07-14', name: '棉铃虫', count: '4' },
    { date: '2025-07-14', name: '暗黑鳃金龟', count: '24' },
    { date: '2025-07-15', name: '铜绿异丽金龟', count: '39' },
    { date: '2025-07-15', name: '小地老虎', count: '10' },
    { date: '2025-07-15', name: '二点委夜蛾', count: '26' },
    { date: '2025-07-16', name: '小地老虎', count: '10' },
    { date: '2025-07-17', name: '二点委夜蛾', count: '36' },
    { date: '2025-07-17', name: '小地老虎', count: '15' },
    { date: '2025-07-18', name: '二点委夜蛾', count: '56' }
  ],
  chartOption: {},
  legendList: [] as string[]
})

const {
  searchFrom,
  insectList,
  typeList,
  totals,
  insectSituationList,
  multipleSelection,
  echartsList,
  chartOption,
  legendList
} = toRefs(state)

const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  }
})

const dialogVisible = ref(props.dialogVisible)
const tableChart = ref()

// onBeforeMount(() => {
//   dialogVisible.value = props.dialogVisible
// })

onMounted(() => {
  setTimeout(() => {
    init()
  }, 500)
})

//查询echarts数据
const getEchatsInfo = async () => {}

//画图
const init = () => {
  const { xAxisData, seriesinfo } = transformToEchartsFormat(echartsList.value)
  chartOption.value = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: legendList.value,
      left: 'center',
      bottom: 'bottom'
    },
    grid: {
      top: 'middle',
      left: '3%',
      right: '4%',
      bottom: '3%',
      height: '80%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLine: {
        lineStyle: {}
      }
    },
    yAxis: {
      type: 'value',

      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLine: {
        show: false
      },
      nameTextStyle: {
        color: '#999'
      },
      splitArea: {
        show: false
      }
    },
    series: dynamicsSeries(seriesinfo)
  }
  //画图

  if (chartOption.value) {
    const chart = echarts.init(tableChart.value)
    chart.setOption(chartOption.value)
  }
}

//整合数据格式
const transformToEchartsFormat = (data) => {
  // 1. 提取所有不重复的日期作为x轴数据
  const dateSet = new Set(data.map((item) => item.date))
  const xAxisData = Array.from(dateSet).sort()

  // 2. 提取所有昆虫种类名称
  const insectNames = [...new Set(data.map((item) => item.name))]

  // 3. 构建系列数据
  const seriesinfo = insectNames.map((name) => {
    // 按日期顺序填充数据，缺失值补0
    const seriesData = xAxisData.map((date) => {
      const item = data.find((d) => d.date === date && d.name === name)
      return item ? parseInt(item.count) : 0
    })
    return { name, type: 'line', data: seriesData }
  })
  // 4. 返回Echarts标准格式
  legendList.value = seriesinfo.map(
    (info: { name: unknown; type: string; data: number[] }) => info.name as string
  )
  return { xAxisData, seriesinfo }
}

// 动态渲染series
const dynamicsSeries = (value) => {
  return value.map((item) => {
    return {
      name: item.name,
      type: 'line',
      data: item.data,
      lineStyle: {
        normal: {
          width: 2
        }
      },
      itemStyle: {
        normal: {
          borderWidth: 2
        }
      },
      smooth: true
    }
  })
}
//分页-页码
const handleCurrentPageUpdate = (page: number) => {
  searchFrom.value.current = page
  // getEchatsInfo()
}
//分页-一页显示多少条
const handlePageSizeUpdate = (page: number) => {
  searchFrom.value.size = page
  // getEchatsInfo()
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

//关闭弹窗
// eslint-disable-next-line vue/valid-define-emits
const emit = defineEmits()
const close = async () => {
  emit('update:dialogVisible', false)
}
</script>
<style lang="scss" scoped>
.card-container {
  margin: 20px;
}
.chart-container {
  height: 50vh;
  width: 100%;
}
</style>
